﻿using System;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace MatlabBridge
{
    [Serializable]
    public class MatlabException : Exception
    {
        public MatlabException() { }
        public MatlabException(string message) : base(message) { }
        public MatlabException(string message, Exception inner) : base(message, inner) { }
        protected MatlabException(SerializationInfo info, StreamingContext context) : base(info, context) { }

        protected static bool m_IgnoreMatlabExceptions = false;
        public static bool IgnoreMatlabExceptions
        {
            get { return m_IgnoreMatlabExceptions; }
            set { m_IgnoreMatlabExceptions = value; }
        }

        [DebuggerHidden]
        internal static void ThrowException(string message)
        {
            if (m_IgnoreMatlabExceptions) return;
            throw new MatlabException(message);
        }
        [DebuggerHidden]
        internal static IntPtr ThrowException(string message, IntPtr p)
        {
            if (m_IgnoreMatlabExceptions || (p != IntPtr.Zero)) return p;
            throw new MatlabException(message);
        }
        [DebuggerHidden]
        internal static int ThrowException(string message, int p)
        {
            if (m_IgnoreMatlabExceptions || (p != 0)) return p;
            throw new MatlabException(message);
        }
        [DebuggerHidden]
        internal static void ThrowOperationFailedException(string function, int functionResult)
        {
            if (m_IgnoreMatlabExceptions || (functionResult == 0)) return;
            throw new MatlabOperationFailedException(function);
        }
    }

    [Serializable]
    public class MatlabOperationFailedException : MatlabException
    {
        public MatlabOperationFailedException() { }
        public MatlabOperationFailedException(string function) : base(GetMessage(function)) { }
        public MatlabOperationFailedException(string function, Exception inner) : base(GetMessage(function), inner) { }
        protected MatlabOperationFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { }

        private static string GetMessage(string function)
        {
            return string.Format("The Matlab C API function '{0}' failed.", function);
        }
    }
}
